<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NEllipsis,
  NDatePicker,
  NTreeSelect,
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { baseDonateCertificateModel } from '@/api/baseDonateCertificate'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const listOption = ref([])
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const tableData = ref<baseDonateCertificateModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const datetime = ref(null)
const modalVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    startDate: null,
    endDate: null,
    topicName: null,
    collectTypeCode: null,
    createdBy: null,
  }),
  () => {
    datetime.value = null
    form.startDate = null
    form.endDate = null
    form.topicName = null
    form.collectTypeCode = null
    form.createdBy = null
  }
)
const columns: DataTableColumns<baseDonateCertificateModel> = [
  {
    title: '主题词',
    key: 'topicName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '类型',
    key: 'collectTypeName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '创建人',
    key: 'createdBy',
    width: '10rem',
    align: 'center'
  },
  {
    title: '创建时间',
    key: 'createdTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '修改时间',
    key: 'updatedTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '备注',
    key: 'remark',
    width: '15rem',
    align: 'center',
    render: (e: any) => {
      return h(
        NEllipsis,
        {
          style: {
            minWidth: '15rem'
          }
        },
        {
          default: () => e.remark
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleEdit(e)
        },
        {
          default: () => '编辑'
        }
      ),

      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(e.id)
        },
        {
          default: () => '删除'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      ),
    ]
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<baseDonateCertificateModel>>({
    module: 'themeWord',
    api: 'list',
    override: {
      params: {
         collectTypeCode:form.collectTypeCode,
         topicName:form.topicName,
        createdBy: form.createdBy,
        startTime: form.startDate,
        endTime: form.endDate,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value =  res.data.list
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A61'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const handleEdit = (e: any) => {
  router.push({ name: 'ThemeConfigEdit', params: { id: e.id } })
}
const handleDetail = (e: any) => {
  router.push({ name: 'ThemeConfigDetail', params: { id: e.id } })
}
const handleAdd = () => {
  router.push({ name: 'ThemeConfigAdd' })
}
const changeDate = (v: any) => {
  datetime.value = v
  form.startDate = v ? v[0] : null
  form.endDate = v ? v[1] : null
}
const ids = ref()
const idDDel = ref(false)
const handleDelete = (id: any) => {
  ids.value = id
  idDDel.value = false
  modalVisible.value = true
}
const againDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'themeWord',
    api: 'delete',
    override: {
      data:{ data:deleteId.value.length > 0 && idDDel.value ? deleteId.value : [ids.value]}
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalVisible.value = false
  message.success('删除成功！')
  rowKeys.value = []
  deleteId.value = []
}
const rowKey: any = (row: any) => row.id || ''
const rowKeys = ref([])
const deleteId = ref([])
const rowKeysChange = (v: any) => {
  rowKeys.value = v
  deleteId.value = v
}
// 版本类型下拉框
const versionTypeOptions = ref([])
const versionTypeLoading = ref(false)
const queryVersionTypeOptions = async (code?: string) => {
  versionTypeLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'collection',
      api: 'typeSelectByCode',
      override: {
        params: {
          parentCode: code
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    res.data.forEach((e) => (e.isLeaf = false))
    return res.data.length ? res.data : undefined
  } catch (error) {
    console.error(error)
  } finally {
    versionTypeLoading.value = false
  }
}
const handleVersionSelectLoad = async (option: any) => {
  const child = await queryVersionTypeOptions(option.value as string)
  if (!child) option.isLeaf = true
  option.children = child
}

onMounted(() => {
  getFunction()
  queryTableData(true)
  queryVersionTypeOptions().then((e) => (versionTypeOptions.value = e || []))
})
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (route.path == '/collectionManagement/CollectionManage/ThemeConfig/index') {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline class="collector-form">
          <NFormItem label="主题词:">
            <NInput placeholder="输入主题词" v-model:value="form.topicName" />
          </NFormItem>
          <NFormItem label="版本类型：">
            <NTreeSelect v-model:value="form.collectTypeCode" :options="versionTypeOptions"
              :loading="versionTypeLoading" :on-load="handleVersionSelectLoad" placeholder="请选择" clearable
              style='width:200px' label-field="label" key-field="value" :consistent-menu-width="false" />
          </NFormItem>
          <NFormItem label="创建人:">
            <NInput placeholder="输入创建人" v-model:value="form.createdBy" />
          </NFormItem>
          <NFormItem label="创建时间:">
            <NDatePicker  v-model:formatted-value="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange" @update:formatted-value="changeDate" clearable='true' />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" style="width: 78px; margin-right: 10px" ghost @click="queryTableData(true)"
              :loading="tableLoading">
              查询
            </NButton>
            <NButton type="primary" ghost style="width: 78px" @click="resetForm">
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton type="primary" style="width: 115px" @click="handleAdd">
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <NDataTable v-bind="props" :data="tableData" :columns="columns" :loading="tableLoading" size="small"
        :bordered="false" :rowKey="rowKey" :checked-row-keys="rowKeys" @update:checked-row-keys="rowKeysChange" />
    </template>
    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againDelete" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
